# app/controllers/family/recipe.py
from typing import List, Optional, Tuple
from app.utils.request import RequestHandler
from app.core.crud import CRUDBase
from app.models.family.recipe import Recipe
from app.schemas.family.recipe import RecipeCreate, RecipeUpdate
from app.services.family.recipe import recipe_service
from app.schemas.base.error_code import *
from app.core.exceptions import BusinessError
from app.utils.app_log import logger
from tortoise.expressions import Q

class RecipeController():
    async def recipe_list(self, page: int, page_size: int, q: Q) -> Tuple[int, List[dict]]:
        """获取食谱列表"""
        try:
            total, recipe_objs = await recipe_service.list(page=page, page_size=page_size, search=q)
            data = [await obj.to_dict() for obj in recipe_objs]
            return total, data
        except Exception as e:
            raise BusinessError(RESOURCE_ACCESS_DENIED, details=f"获取食谱列表出错：{str(e)}")

    async def get_recipe_info(self, recipe_id: int, family_id: int) -> dict:
        """获取食谱详情"""
        try:
            
            recipe_obj = await recipe_service.get_recipe_by_family(recipe_id, family_id)
            if not recipe_obj:
                raise BusinessError(RESOURCE_NOT_FOUND.format(resource="食谱"), details="食谱不存在")
            recipe_dict = await recipe_obj.to_dict()
            return recipe_dict
        except Exception as e:
            raise BusinessError(RESOURCE_NOT_FOUND.format(resource="食谱"), details=f"食谱不存在：{str(e)}")

    async def remove_recipe(self, recipe_id: int, family_id: int) -> bool:
        """删除食谱"""
        try:
            
            recipe_obj = await recipe_service.get_recipe_by_family(recipe_id, family_id)
            if not recipe_obj:
                raise BusinessError(RESOURCE_NOT_FOUND.format(resource="食谱"), details="食谱不存在")
            await recipe_service.remove(recipe_id)
            return True
        except Exception as e:
            raise BusinessError(RESOURCE_DELETE_FAILED.format(resource="食谱"), details=f"删除食谱失败 {str(e)}")

    async def create_recipe(self, recipe_in: RecipeCreate) -> Recipe:
        """创建食谱"""
        try:
            # 检查同名食谱是否已存在
            existing_recipe = await recipe_service.model.filter(
                name=recipe_in.name, 
                family_id=recipe_in.family_id,
                is_deleted=False
            ).first()
            if existing_recipe:
                raise BusinessError(RESOURCE_ALREADY_EXISTS.format(resource="食谱"), details="该食谱名称已存在")
            
            new_recipe = await recipe_service.create(recipe_in)
            return new_recipe
        except Exception as e:
            raise BusinessError(RESOURCE_CREATE_FAILED.format(resource="食谱"), details=f"创建食谱失败 {str(e)}")

    async def update_recipe_info(self, recipe_id: int, obj_in: RecipeUpdate, family_id: int) -> bool:
        """更新食谱信息"""
        try:
            
            recipe_obj = await recipe_service.get_recipe_by_family(recipe_id, family_id)
            if not recipe_obj:
                raise BusinessError(RESOURCE_NOT_FOUND.format(resource="食谱"), details="食谱不存在")
            await recipe_service.update(recipe_id, obj_in)
            return True
        except Exception as e:
            raise BusinessError(RESOURCE_UPDATE_FAILED.format(resource="食谱"), details=f"更新食谱失败 {str(e)}")

recipe_controller = RecipeController()